
from sanic import response
from services import file_service


# 文件下载API
def setup_file_download_routes(bp):
    """设置文件下载路由"""
    
    @bp.get('/get_file/<filename>')
    async def get_file(request, filename):
        """通过文件名获取文件并下载"""
        # 调用服务层获取文件信息
        result = await file_service.get_file_by_filename(filename)
        
        # 检查是否获取成功
        if result['code'] != 200:
            return response.json(result)
        
        # 获取文件数据和名称
        file_info = result['data']
        file_data = file_info['file_data']
        original_filename = file_info['filename']
        file_size = file_info['file_size']
        
        # 返回文件下载响应，使用原始文件名
        return response.raw(
            file_data,
            headers={
                'Content-Disposition': f'attachment; filename="{original_filename}"',
                'Content-Type': 'application/octet-stream',
                'Content-Length': str(file_size)
            }
        )